package com.mysterymall.Controller;
import org.apache.tika.Tika;
import com.mysterymall.Common.Comp.HttpStatus;
import com.mysterymall.Common.Comp.Log;
import com.mysterymall.Common.Utils.Result;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.FilenameUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.validation.Valid;
import java.io.*;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
import java.util.Arrays;
import java.util.List;
import java.util.UUID;

/**
 * @ClassName com.mysterymall.Controller
 * @Description
 * @Author HuangWX
 * @Time 2023/11/08  01:52
 */
@RestController
@RequestMapping("/upload")
@Slf4j
public class UploadingCont {


    @Value("${mystery.rootPath}")
    private String rootPath;


    // 上传大小限制
    private static final long MAX_FILE_SIZE = 5 * 1024 * 1024; // 5MB


    // 限制视频文件大小为200MB
    private static final long VIDEO_MAX_FILE_SIZE = 200 * 1024 * 1024;

    // 类型限制
    private static final List<String> ALLOWED_EXTENSIONS = Arrays.asList("png", "jpg");

    @PostMapping("/image")
    @Log
    public Result uploadImage(@RequestParam("file") MultipartFile file) throws IOException {

        if(file.isEmpty()){
            return  new Result(402,"message.upload.imageEmptyError");
        }

        if (file.getSize() > MAX_FILE_SIZE) {
            return  new Result(402,"message.upload.imagesSizeError");
        }

        String originalFilename = file.getOriginalFilename();
        String fileExtension = originalFilename.substring(originalFilename.lastIndexOf(".") + 1);

        if (!ALLOWED_EXTENSIONS.contains(fileExtension.toLowerCase())) {
            return new Result(402,"message.upload.imagesClassError");
        }

        // 保存上传的文件到服务器
        String fileName = UUID.randomUUID().toString() + "." +  fileExtension;
        File uploadedFile = new File(rootPath + fileName);
        FileOutputStream fileOutputStream = new FileOutputStream(uploadedFile);
        fileOutputStream.write(file.getBytes());
        fileOutputStream.close();

        return new Result(200,"message.addSuccess",fileName);
    }


    @PostMapping("/video")
    @Log
    public Result uploadVideo(@RequestParam("file") MultipartFile file) throws IOException {

        if (file.isEmpty()) {
            return new Result(HttpStatus.BAD_NOT_PASS, "message.queryError-文件不存在");
        }

        // 检查文件大小
        if (file.getSize() > VIDEO_MAX_FILE_SIZE) {
            return new Result(HttpStatus.BAD_NOT_PASS, "message.queryError-不能超过200MB");
        }

        Tika tika = new Tika();
        String detectedType = tika.detect(file.getInputStream());

        // 获取文件的输入流
        InputStream inputStream = file.getInputStream();

        // 检查文件类型是否为视频
        if (detectedType != null && detectedType.startsWith("video/")) {
            // 进一步检查文件头信息，可以根据实际需求添加其他视频格式的标识符
            byte[] headerBytes = new byte[8];
            inputStream.read(headerBytes);
            Path uploadPath = Paths.get(rootPath);
            String originalFilename = file.getOriginalFilename();
            String fileExtension = "";
            if (originalFilename != null && originalFilename.contains(".")) {
                fileExtension = FilenameUtils.getExtension(originalFilename);
            }
            String fileName = UUID.randomUUID() + (fileExtension.isEmpty() ? "" : ("." + fileExtension));
            Path filePath = uploadPath.resolve(fileName);
            // 保存文件到指定路径
            try (InputStream inputStreamSave = file.getInputStream()) {
                Files.copy(inputStreamSave, filePath, StandardCopyOption.REPLACE_EXISTING);
                return new Result(HttpStatus.SUCCESS, "message.addSuccess",fileName);
            }catch (IOException e) {
                // 适当处理异常
                log.error("文件上传失败", e);
                throw new RuntimeException();
            }

        }

        return new Result(HttpStatus.BAD_NOT_PASS, "message.upload.videoClassError");

    }
}
